<template>
  <view class="container">
	  <canvas canvas-id="snow-canvas" class="snow-canvas"></canvas>
    <!-- 顶部头像区域 -->
    <view class="header">
      <view class="avatar-wrapper">
        <image 
          :src="form.avatar || '/static/default_avatar.jpg'" 
          class="avatar" 
          @click="chooseAvatar"
        ></image>
        <view class="upload-btn">更换头像</view>
      </view>
      <view class="user-name">{{ form.nickname || '点击修改昵称' }}</view>
    </view>

    <!-- 信息编辑表单 -->
    <form @submit="onSubmit">
      <!-- 昵称 -->
      <view class="form-item">
        <label class="label">昵称</label>
        <input 
          type="text" 
          v-model="form.nickname" 
          placeholder="请输入昵称（最多12字）" 
          maxlength="12"
        />
      </view>

      <!-- 真实姓名 -->
      <view class="form-item">
        <label class="label">真实姓名</label>
        <input 
          type="text" 
          v-model="form.real_name" 
          placeholder="选填"
        />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <label class="label">手机号</label>
        <input 
          type="number" 
          v-model="form.phone" 
          placeholder="请输入手机号"/>
      </view>

      <!-- 学院/专业 -->
	  <view class="form-item">
	    <label class="label">学院</label>
	    <view class="row">
	      <picker
	      			mode="selector" 
	      			:range="colleges" 
	      			:value="collegeIndex" 
	      			@change="onCollegeChange"
	      >
	      			<view class="picker-view">
	      			  {{ form.college || '请选择学院' }}
	      			</view>
	      </picker>
	      
	    </view>
	  </view>
      <view class="form-item">
        <label class="label">专业</label>
        <view class="row">
          <input 
            type="text" 
            v-model="form.major" 
            placeholder="专业"
            class="half-input"
          />
        </view>
      </view>

      <!-- 年级/宿舍 -->
	   
      <view class="form-item">
        <label class="label">年级</label>
        <view class="row">
          <picker 
			  mode="selector" 
			  :range="grades" 
			  :value="gradeIndex" 
			  @change="onGradeChange"
			>
			  <view class="picker-view">
				{{ grades[gradeIndex] || '请选择年级' }}
			  </view>
			</picker>
          
        </view>
      </view>
	  <view class="form-item">
	     <label class="label">宿舍</label>
	     <input
	       type="text" 
	       v-model="form.dormitory" 
	       placeholder="宿舍"
	       class="half-input"
	     />
	   </view>

      <!-- 个人简介 -->
      <view class="form-item">
        <label class="label">个人简介</label>
        <textarea 
          v-model="form.bio" 
          placeholder="一句话介绍自己（最多200字）" 
          maxlength="200"
          rows="3"
        ></textarea>
      </view>

      <!-- 提交按钮 -->
      <button 
        type="primary" 
        class="submit-btn" 
        form-type="submit"
      >
        保存修改
      </button>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
     
	  colleges: [],
	  collegeIndex:'',
	  gradeIndex:0,
	  grades: [], // 动态生成的年级列表
      form: {
        nickname: '',
        real_name: '',
        phone: '',
        college: '',
        major: '',
        grade: '',
        dormitory: '',
        bio: ''
      }
    };
  },
  onLoad() {
    // 初始化表单数据（实际需从接口获取用户信息）
	this.getUserInfo()
    this.form = {
      ...this.form,
      phone: this.form.phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') // 脱敏显示
    };
	this.generateGradeOptions();
	this.getShool()
	
  },
  onReady() {
  	this.initSnowEffect();
  },
  methods: {
	async  getShool(){
		const res = await this.$api.get('/School/list')
		if(res.data.code === 200) {
			this.list = res.data.data
			res.data.data.forEach(item => {
				this.colleges.push(item.school_name)
			})
		}
	},
	async getUserInfo(){
		const res = await this.$api.get('/user/getInfo')
		if(res.data.code == 200){
			this.form = res.data.data
			// const defaultIndex = this.colleges.indexOf(this.form.college);
			// this.collegeIndex = defaultIndex >= 0 ? defaultIndex : 0;
			// this.form.college = this.colleges[this.collegeIndex];
			const dIndex = this.grades.indexOf(this.form.grade);
			this.gradeIndex = dIndex >= 0 ? dIndex : 0;
			this.form.grade = this.grades[this.gradeIndex];
		}
	},
	initSnowEffect() {
		const sys = uni.getSystemInfoSync();
		const W = sys.windowWidth;
		const H = sys.windowHeight;
		const ctx = uni.createCanvasContext('snow-canvas', this);
		const snowflakes = Array.from({
			length: 35
		}, () => ({
			x: Math.random() * W,
			y: Math.random() * H,
			r: Math.random() * 2.5 + 1,
			d: Math.random() * 1.5 + 0.5
		}));
	
		const draw = () => {
			ctx.clearRect(0, 0, W, H);
			ctx.setFillStyle('rgba(255,255,255,0.8)');
			ctx.beginPath();
			snowflakes.forEach(flake => {
				ctx.moveTo(flake.x, flake.y);
				ctx.arc(flake.x, flake.y, flake.r, 0, Math.PI * 2);
			});
			ctx.fill();
			snowflakes.forEach(flake => {
				flake.y += flake.d;
				flake.x += Math.sin(flake.y / 30) * 0.6;
				if (flake.y > H) {
					flake.y = 0;
					flake.x = Math.random() * W;
				}
			});
			ctx.draw();
			// #ifdef H5
			requestAnimationFrame(draw);
			// #endif
			// #ifdef MP-WEIXIN
			setTimeout(draw, 1000 / 60);
			// #endif
		};
		draw();
	},
	// 自动生成年级选项（基于当前年份）
	generateGradeOptions() {
	  const currentYear = new Date().getFullYear();
	  const gradeOptions = [];
	  
	  // 生成当前年份及前5年的年级选项
	  for (let i = 0; i < 6; i++) {
		const year = currentYear - i;
		gradeOptions.push(`${year}级`);
	  }
	  
	  this.grades = gradeOptions;
	},
	
	// 年级选择变化事件
	onGradeChange(e) {
	  this.gradeIndex = e.target.value;
	  this.form.grade = this.grades[this.gradeIndex];
	},
	onCollegeChange(e) {
	  this.collegeIndex = e.target.value;
	  this.form.college = this.colleges[this.collegeIndex];
	  this.form.school_id = this.list[this.collegeIndex].school_id
	},
    // 选择头像
    async chooseAvatar() {
      uni.chooseImage({
        count: 1,
        success:  (res)  => {
          const tempFilePaths = res.tempFilePaths;
		  this.$api.uploadFile('/upload/File',tempFilePaths[0]).then(res => {
		   if(res.code === 200) {
			   this.form.avatar = res.url;
		   } else {
			   uni.showToast({
			   	icon:'none',
				title:'图片内容违反规定，无法上传'
			   })
		   }
		  })
        }
      });
    },
    // 提交表单
    async onSubmit() {
      // 数据验证
      if (!this.form.nickname) {
        uni.showToast({ title: '请填写昵称', icon: 'none' });
        return;
      }
	  if (!this.form.college) {
	    uni.showToast({ title: '请选择学校', icon: 'none' });
	    return;
	  }
	  if (!this.form.major) {
	    uni.showToast({ title: '请填写专业', icon: 'none' });
	    return;
	  }
	  if (!this.form.grade) {
	    uni.showToast({ title: '请选择年级', icon: 'none' });
	    return;
	  }

      // 调用接口更新用户信息（需替换为实际接口）
	  const res = await this.$api.post('/user/updateInfo',this.form,true)
	  if(res.data.code == 200) {
		  console.log(res.data,'fsfsdfds')
		  uni.showToast({
		  	icon:'none',
			title:res.data.msg
		  })
		  this.getUserInfo()
	  }
      
    }
  }
};
</script>

<style scoped lang="scss">
.container {
  // background-color: #f5f7fa;
  padding: 20rpx;
  flex: 1;
  position: relative;
  min-height: 100vh;
  background: linear-gradient(to bottom, #e0f7fa, #ffffff);
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.avatar-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  font-size: 24rpx;
  text-align: center;
  padding: 4rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.form-item {
  background-color: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  padding: 30rpx 25rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
  display: block;
}

input, textarea {
  width: 100%;
  font-size: 30rpx;
  color: #333;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

input::placeholder, textarea::placeholder {
  color: #999;
}

.row {
  display: flex;
  justify-content: space-between;
}

.half-input {
  width: 48%;
}

textarea {
  height: 150rpx;
  resize: none;
}

.submit-btn {
  background-color: #409eff;
  border-radius: 30rpx;
  padding: 25rpx;
  margin-top: 40rpx;
  font-size: 32rpx;
  box-shadow: 0 6rpx 18rpx rgba(64, 158, 255, 0.2);
  border: none;
}

button::after {
  border: none; /* 移除默认边框 */
}
</style>